package com.lemo.controllor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.ModelAndView;

import com.lemo.entity.User;

@Controller
@RequestMapping("/user")
public class UserControllor {
	
	
	@RequestMapping("login")
	public String login(User user, HttpServletRequest request) {
		Subject currentUser = SecurityUtils.getSubject();
		if (!currentUser.isAuthenticated()) {
			UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword());
			String rememberMe = request.getParameter("rememberMe");
			boolean remembered = currentUser.isRemembered();
			System.out.println(remembered);
			if (rememberMe != null) {
				token.setRememberMe(true);
			}
			try {
				currentUser.login(token);
				Session session = currentUser.getSession();
				session.setAttribute("currentUser", currentUser);
			} catch (AuthenticationException e) {
				System.out.println("登录失败！");
				request.setAttribute("errorMsg", "用户名或密码错误");
				return "index";
			}
		}
		return "redirect:/list.jsp";
	}

	@ExceptionHandler({ Exception.class })
	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	public ModelAndView processUnauthenticatedException(NativeWebRequest request, UnauthorizedException ex) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("msg", ex);
		// 为了区分，跳转掉另一个视图
		mv.setViewName("/noRole");
		return mv;
	}

}
